package sopt.dev.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import sopt.dev.R;
import sopt.dev.data.CityVO;
import sopt.dev.data.CropOption;
import sopt.dev.data.CropOptionAdapter;
import sopt.dev.data.GagebuDataModel;
import sopt.dev.data.ItemVO;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

public class CityAddActivity extends Activity implements OnClickListener {
	// DatePicker 변수
	private TextView tvFrom, tvTo;
	private AutoCompleteTextView edtCityName;
	private int year;
	private int month;
	private int day;
	private Spinner mCityMoney;

	private static final int DATE_DIALOG_ID_FROM = 1;
	private static final int DATE_DIALOG_ID_TO = 2;

	// 카메라 변수
	private Uri mImageCaptureUri; // 카메라, 갤러리 파일 경로
	private ImageView mImageView;
	private static final int PICK_FROM_CAMERA = 1;
	private static final int CROP_FROM_CAMERA = 2;
	private static final int PICK_FROM_FILE = 3;
	private AlertDialog.Builder builder;
	private AlertDialog dialog;
	private CityVO<ItemVO> data;
	private int clickedPosition = 0;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.city_add_activity);

		Button btnFrom, btnTo;

		edtCityName = (AutoCompleteTextView) findViewById(R.id.city_add_cityname);
		String[] items = { "London", "런던 ", "CamBridge", "캠브리지", "Oxford",
				"옥스포드", "Hampton court", "햄튼 코트", "Brussels", "브뤼셀", "Brugge",
				"브뤼헤", "Amsterdam", "암스테르담", "Berlin", "베를린", "Munchen", "뮌헨",
				"Fussen", "퓌센", "Heidelberg", "하이델베르크", "Frankfurt", "프랑크푸르트",
				"Rothenburg", "로텐부르크", "Hanover", "하노버", "Leipzig", "라이프치히",
				"Praha", "프라하", "Warszawa", "바르샤바", "Krakow", "크라쿠프",
				"Budapest", "부다페스트", "Wien", "빈", "Innsbruck", "인스부르크",
				"Salzburg", "짤츠부르크", "Hallstatt", "할슈타트", "Roma", "로마",
				"Napoli", "나폴리", "Pompei", "Assisi", "아씨씨", "Venezia", "베네치아",
				"Firenze", "피렌체", "Pisa", "피사", "Siena", "씨에나", "Milano",
				"밀라노", "Bern", "베른", "Zurich", "취리히", "Luzern", "루체른",
				"Lugano", "루가노", "Zermartt", "체르마트", "Interlaken", "인터라켄",
				"Montreux", "몽뜨뢰", "Laussane", "로잔", "Geneve", "제네바", "Basel",
				"바젤", "Liechtenstein", "리히텐슈타인", "Barcelona", "Montserrat",
				"몬세라", "Madrid", "마드리드", "Toledo", "똘레도", "Paris", "파리",
				"Versailles", "베르사유", "Mont st.Michel", "몽샐미쉘", "Nice", "니스",
				"Monaco", "모나코" };
		edtCityName.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, items));

		mImageView = (ImageView) findViewById(R.id.city_add_iv_photo);
		mImageView.setOnClickListener(this);

		mCityMoney = (Spinner) findViewById(R.id.city_add_spin_exchange);

		Button btn_cancel = (Button) findViewById(R.id.city_add_btn_cel);
		btn_cancel.setOnClickListener(this);

		Button btn_ok = (Button) findViewById(R.id.city_add_btn_ok);
		btn_ok.setOnClickListener(this);

		// 여행시작날짜

		tvFrom = (TextView) findViewById(R.id.city_add_tv_from);
		btnFrom = (Button) findViewById(R.id.city_add_btn_from);
		btnFrom.setOnClickListener(this);

		// 여행종료날짜
		tvTo = (TextView) findViewById(R.id.city_add_tv_to);
		btnTo = (Button) findViewById(R.id.city_add_btn_to);
		btnTo.setOnClickListener(this);

		// 날짜 초기화
		initCalendar();

		// ImagePicker 초기화
		initImagePicker();

		initSpinner();

		data = getDataFromIntent();
		clickedPosition = getClickedPosition();
		
		// intent 로 부터 데이터를 받아들임
		try {
			if (data != null) {
			
			edtCityName.setText(data.getCityName());
			tvFrom.setText(data.getInString());
			tvTo.setText(data.getOutString());
			}
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}

	private void initSpinner() {
		ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter
				.createFromResource(this, R.array.exchange_rate,
						android.R.layout.simple_spinner_item);

		arrayAdapter
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		Spinner spinner = (Spinner) findViewById(R.id.city_add_spin_exchange);
		spinner.setAdapter(arrayAdapter);
	}

	private void initCalendar() {
		final Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);
	}

	private CityVO<ItemVO> getDataFromIntent() {
		return (CityVO<ItemVO>) getIntent().getParcelableExtra( "city_data" );
	}

	private int getClickedPosition() {
		return getIntent().getIntExtra( "position", -1 );		
	}
	
	private void initImagePicker() {
		/*
		 * imagePicker & crop from gallery
		 */
		// 카메라 촬영 or 갤러리에서 가져오기 선택 dialog
		final String[] items = new String[] { "Take from camera",
		"Select from gallery" };
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.select_dialog_item, items);
		builder = new AlertDialog.Builder(this);

		builder.setTitle("Select Image");
		builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				// pick from camera
				if (item == 0) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

					mImageCaptureUri = Uri.fromFile(new File(Environment
							.getExternalStorageDirectory(), "tmp_avatar_"
									+ String.valueOf(System.currentTimeMillis())
									+ ".jpg"));

					intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
							mImageCaptureUri);

					try {
						intent.putExtra("return-data", true);

						startActivityForResult(intent, PICK_FROM_CAMERA);
					} catch (ActivityNotFoundException e) {
						e.printStackTrace();
					}
				} else { // pick from file
					Intent intent = new Intent();

					intent.setType("image/*");
					intent.setAction(Intent.ACTION_GET_CONTENT);

					startActivityForResult(Intent.createChooser(intent,
							"Complete action using"), PICK_FROM_FILE);
				}
			}
		});
	}

	// TODO deprecated된 함수 다른 것을 알아볼
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID_FROM:
			return new DatePickerDialog(this, mDateSetListenerFrom, year,
					month, day);
		case DATE_DIALOG_ID_TO:
			return new DatePickerDialog(this, mDateSetListenerTo, year, month,
					day);
		}
		return null;
	}

	// updates the date we display in the TextView
	private void updateDisplayFrom() {
		tvFrom.setText(new StringBuilder()
		// Month is 0 based so add 1
		.append(year).append("-").append(month + 1).append("-")
		.append(day).append(""));
	}

	private void updateDisplayTo() {
		tvTo.setText(new StringBuilder()
		// Month is 0 based so add 1
		.append(year).append("-").append(month + 1).append("-")
		.append(day).append(""));
	}

	private DatePickerDialog.OnDateSetListener mDateSetListenerFrom = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int myear, int monthOfYear,
				int dayOfMonth) {
			year = myear;
			month = monthOfYear;
			day = dayOfMonth;
			updateDisplayFrom();
		}
	};

	private DatePickerDialog.OnDateSetListener mDateSetListenerTo = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int myear, int monthOfYear,
				int dayOfMonth) {
			year = myear;
			month = monthOfYear;
			day = dayOfMonth;
			updateDisplayTo();
		}
	};

	/*
	 * DatePicker finish
	 */

	/*
	 * imagePicker & crop from gallery
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK)
			return;

		switch (requestCode) {
		case PICK_FROM_CAMERA:
			doCrop();

			break;

		case PICK_FROM_FILE:
			mImageCaptureUri = data.getData();

			doCrop();

			break;

		case CROP_FROM_CAMERA:
			Bundle extras = data.getExtras();

			if (extras != null) {
				// crop 된 파일 저장
				Bitmap photo = extras.getParcelable("data");

				mImageView.setImageBitmap(photo);
			}

			File f = new File(mImageCaptureUri.getPath());

			if (f.exists()) {
				boolean delete = f.delete();
			}

			break;

		}
	}

	private void doCrop() {
		final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setType("image/*");

		List<ResolveInfo> list = getPackageManager().queryIntentActivities(
				intent, 0);

		int size = list.size();

		if (size != 0) {

			intent.setData(mImageCaptureUri);

			intent.putExtra("outputX", 200);
			intent.putExtra("outputY", 200);
			intent.putExtra("aspectX", 3);
			intent.putExtra("aspectY", 1);
			intent.putExtra("scale", false);
			intent.putExtra("return-data", true);

			if (size == 1) {
				Intent i = new Intent(intent);
				ResolveInfo res = list.get(0);

				i.setComponent(new ComponentName(res.activityInfo.packageName,
						res.activityInfo.name));

				startActivityForResult(i, CROP_FROM_CAMERA);
			} else {
				for (ResolveInfo res : list) {
					final CropOption co = new CropOption();

					co.title = getPackageManager().getApplicationLabel(
							res.activityInfo.applicationInfo);
					co.icon = getPackageManager().getApplicationIcon(
							res.activityInfo.applicationInfo);
					co.appIntent = new Intent(intent);

					co.appIntent
					.setComponent(new ComponentName(
							res.activityInfo.packageName,
							res.activityInfo.name));

					cropOptions.add(co);
				}

				CropOptionAdapter adapter = new CropOptionAdapter(
						getApplicationContext(), cropOptions);

				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("Choose Crop App");
				builder.setAdapter(adapter,
						new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						startActivityForResult(
								cropOptions.get(item).appIntent,
								CROP_FROM_CAMERA);
					}
				});

				builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {

						if (mImageCaptureUri != null) {
							getContentResolver().delete(mImageCaptureUri, null,
									null);
							mImageCaptureUri = null;
						}
					}
				});

				AlertDialog alert = builder.create();

				alert.show();
			}

		}
	}

	public void onClick(View view) {

		switch (view.getId()) {

		case R.id.city_add_btn_ok: {
			String cityName = null;
			String inDate = null;
			String outDate = null ;
			int cityMoney ;
			String imgPath = "";
			
			try {
				cityName = edtCityName.getText().toString();
				inDate = tvFrom.getText().toString();
				outDate = tvTo.getText().toString();
				cityMoney = Integer.parseInt(mCityMoney.getSelectedItem().toString());
			} catch(NullPointerException e) {
				cityName = "";
				inDate = "";
				outDate = "";
				cityMoney = 0;
			} catch(NumberFormatException e) {
				cityMoney = 0;
			}
			
			CityVO<ItemVO> city = new CityVO<ItemVO>(
					imgPath, cityName, cityMoney, inDate,
					outDate);
					
			// click 되어서 넘어온 도시가 아니면
			if(clickedPosition == -1) {
				GagebuDataModel.getInstance().addCity(city);
			} else {	
				// 넘어온 도시 정보 업데이트
				GagebuDataModel.getInstance().updateCity(city, clickedPosition);
			}
				
			startActivity(new Intent(this, CityListActivity.class));
			finish();

			break;
		}

		case R.id.city_add_btn_from: {
			showDialog(DATE_DIALOG_ID_FROM);
			break;
		}

		case R.id.city_add_btn_to: {
			showDialog(DATE_DIALOG_ID_TO);
			break;
		}

		case R.id.city_add_iv_photo: {
			dialog = builder.create();
			dialog.show();
			break;
		}

		case R.id.city_add_btn_cel: {
			finish();
			break;
		}

		}
	}
}
